package com.jerei.web.utils.ui;

import com.alibaba.fastjson.JSONArray;
import com.jerei.utils.UtilsCommon;
import freemarker.core.Environment;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

/**
 * Created by sunfeihu on 2016/11/5.
 */
@Component
public class FormForEditTag implements TemplateDirectiveModel {

    @Override
    public void execute(Environment env, Map params, TemplateModel[] models, TemplateDirectiveBody body) throws TemplateException, IOException {
        Writer out = env.getOut();
        String formsStr = UtilsCommon.getString(params.get("forms"));
        BeansWrapper beansWrapper = new BeansWrapperBuilder(Configuration.getVersion()).build();
        if (null != formsStr && !"".equals(formsStr)) {
            JSONArray formsArr = JSONArray.parseArray(formsStr);
            env.setLocalVariable("forms", beansWrapper.wrap(formsArr));
        }
        if (body != null) {
            body.render(env.getOut());
        } else {
            throw new RuntimeException("标签内部至少要加一个空格");
        }
    }
}
